<?php

namespace PointPresse\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use PointPresse\BlogBundle\Entity\Post;
use PointPresse\BlogBundle\Entity\Journalist;
use Symfony\Component\HttpFoundation\Session\Session;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

use PointPresse\BlogBundle\Form\PostType;

class BlogController extends Controller {

    public function indexAction() {
        
    }

    public function accueilAction() {
        
        $route =$this->getRequest()->getUri();
        $this->getRequest()->getSession()->set('route',$route);
                
        
        $this->getCategories();
        
        $userId=$this->getUser()->getId();
        
        $this->getPosts();
        
   
        
        //recuperation des brouillons
        $repository = $this->getDoctrine()
                   ->getManager()
                   ->getRepository('PointPresseBlogBundle:Post');
 
        $listPosts = $repository->myFindAll();

        //var_dump($this->getRequest()->getSession()->get('tabPostsSent'));
        //var_dump($this->getRequest()->getSession()->get('tabPostsPublished'));
        return $this->render('PointPresseBlogBundle:Blog:index.html.twig', array(
                    'posts' => $listPosts,
                    'tabPostsSent' => $this->getRequest()->getSession()->get('tabPostsSent'),
                    'tabPostsPublished' => $this->getRequest()->getSession()->get('tabPostsPublished')
                    
                ));
    }

    public function readAction($page) {
        $route =$this->getRequest()->getUri();
       // $route = $this->getRequest()->attributes->get('_route');
        $this->getRequest()->getSession()->set('route',$route);
        

        
        $tabSort= array('subject+'=>'Titre (A->Z)',
                        'subject-'=>'Titre (Z->A)',
                        'date+'=>'Date (Récent->Ancien)',
                        'date-'=>'Date (Ancien->Récent)');
        
        $form = $this->createFormBuilder()
        ->add('sort', 'choice', array(
                'choices' =>$tabSort,
                'required' => true,
                'label'=> 'Tri par',
                'multiple' => false))
        
        ->getForm();

        $request = $this->get('request');
        if ($request->getMethod() == 'POST') 
        {
            $form->bind($request);
            
            $data = $form->getData();
            //var_dump($form->getData());
            $userId=$this->getUser()->getId();
            $repository = $this->getDoctrine()
                   ->getManager()
                   ->getRepository('PointPresseBlogBundle:Post');

            $numberPostsPerPage = 2;
                  
            switch($data['sort'])    
            {
                case 'subject+' : 
                    $listPosts = $repository->getPostsByJournalistAndSubject($userId,$page,$numberPostsPerPage,'ASC');
                    break;
                case 'subject-' : 
                    $listPosts = $repository->getPostsByJournalistAndSubject($userId,$page,$numberPostsPerPage,'DESC');
                    break;
                case 'date+' :
                    $listPosts = $repository->getPostsByJournalistAndDate($userId,$page,$numberPostsPerPage,'ASC');
                    break;  
                case 'date-' :
                    $listPosts = $repository->getPostsByJournalistAndDate($userId,$page,$numberPostsPerPage,'DESC');
                    break;                   
                
            }
            
        }      
        
        else
        {
            $userId=$this->getUser()->getId();
            $repository = $this->getDoctrine()
                   ->getManager()
                   ->getRepository('PointPresseBlogBundle:Post');
 
            $numberPostsPerPage = 2;
            $listPosts = $repository->getPostsByJournalist($userId,$page,$numberPostsPerPage);
        }
        

        return $this->render('PointPresseBlogBundle:Blog:listPosts.html.twig', array(
                    'posts' => $listPosts,
                    'page' => $page,
                    'nombrePage' => ceil (count($listPosts)/2),
                    'form' => $form->createView()
                
                ));
    }
    
    
    public function readCatAction($idCat,$page) {
        
        $route =$this->getRequest()->getUri();
        $this->getRequest()->getSession()->set('route',$route);
        
        $session = $this->get('session');
        $categories=$session->get('categories');
        foreach($categories as $id => $nom)
        {
            if($id==$idCat)
            {
               $nomCat= $nom;
            }
        }
        
        $userId=$this->getUser()->getId();
        
        $numberPostsPerPage = 2;
        
        $repository = $this->getDoctrine()
                   ->getManager()
                   ->getRepository('PointPresseBlogBundle:Post');
        
        $listPosts = $repository->getPostsByJournalistAndCategory($userId,$idCat,$page,$numberPostsPerPage);

        
        return $this->render('PointPresseBlogBundle:Blog:listPostsCat.html.twig', array(
                    'posts' => $listPosts,
                    'cat' =>$nomCat,
                    'idCat' => $idCat,
                    'page' => $page,
                    'nombrePage' => ceil (count($listPosts)/2)));
    }

    public function addAction() {
        
        $previousRoute = $this->getRequest()->getSession()->get('route');
        $route =$this->getRequest()->getUri();
        $this->getRequest()->getSession()->set('route',$route);
        
        $session = $this->get('session');
        $categories=$session->get('categories');
            
        $post = new Post();            
        $post->setJournalist($this->getUser());      
        
        $form = $this->createForm(new PostType(array('categories'=>$categories)),$post);
              
            
        

        return $this->render('PointPresseBlogBundle:Blog:addPost.html.twig', array(
                    'form' => $form->createView(),
                    'previousRoute' => $previousRoute
        ));

    }

    public function deleteAction() {
        return $this->render('PointPresseBlogBundle:Blog:index.html.twig');
    }

    
    /**
     * @ParamConverter("post", options={"mapping": {"idPost": "id"}})
    */
    public function modifyAction(Post $post) {
        
        $previousRoute = $this->getRequest()->getSession()->get('route');
        $route =$this->getRequest()->getUri();
        $this->getRequest()->getSession()->set('route',$route);
        
        $session = $this->get('session');
        $categories=$session->get('categories');
            
        $form = $this->createForm(new PostType(array('categories'=>$categories)),$post);
              
           
        $request = $this->get('request');
        if ($request->getMethod() == 'POST') 
        {
            $form->bind($request);

            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                //$em->persist($post);
                $em->flush();
                
                // On définit un message flash
                $this->get('session')->getFlashBag()->add('info', 'Brouillon modifié');

               // return $this->redirect($this->generateUrl('pointPresse_accueil'));
            }
        }

        return $this->render('PointPresseBlogBundle:Blog:modifyPost.html.twig', array(
                    'form' => $form->createView(),
                    'post' => $post,
                    'previousRoute' => $previousRoute
        ));
        
        
        
        
        return $this->render('PointPresseBlogBundle:Blog:index.html.twig');
    }

    public function menuCatAction() {

        
        
        $session = $this->get('session');
        $tabCat=$session->get('categories');
        //echo($categories['category'][2]['name']);
        //echo $categories->{'category'}[1]->{'name'};
       

        return $this->render('PointPresseBlogBundle:Blog:menuCat.html.twig', array(
                    'list_cat' => $tabCat
        ));
    }
    
    public function getCategories()
    {
         //recuperation et traitement categories
        $categories = array(array("idCategory"=>1,"name"=>"sport"),array("idCategory"=>2,"name"=>"info"));
        //$categories = json_decode(file_get_contents('http://192.168.128.13:8081/d110005/category'),true);
        //$categories = $categories['category']; 
        
        
        $tabCat = array();
        foreach($categories as $cat)
        {
            $tabCat[$cat['idCategory']]= $cat['name'];
        }
        $session = $this->get('session');
        $session->set('categories',$tabCat);
        
        
    }
    
    public function getPosts()
    {
        // Base URL for the service
        $baseUrl = 'http://192.168.128.13:8081/d110005/post/findByIdJournalist/1';
        
        $curl = curl_init($baseUrl) ;
       // curl_setopt($curl, CURLOPT_HTTPGET, TRUE); 
       // curl_setopt($curl, CURLOPT_ENCODING, "application/json");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 
        $result = curl_exec($curl);
        curl_close($curl);
        // Print result
        var_dump($result);
        
        $posts = json_decode($result,true);
        
        var_dump($posts);
        
        $test = json_encode($posts);
        
        var_dump($test);
        
        
        
         
          
            /*
             * $url = "http://localhost:8084/ServiceRest/webresources/article/author/" . $journaliste->getPrenom() . "/" . $journaliste->getNom(); 
             * $ch = curl_init($url); 
             curl_setopt($ch, CURLOPT_HTTPGET, TRUE); 
             curl_setopt($ch, CURLOPT_ENCODING, "application/xml"); 
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //permet de retourner le resultat lors du curl_exec au lieu de TRUE en cas de succes. 
             $result = curl_exec($ch); 
             curl_close($ch); 
             $articles = new SimpleXMLElement($result); 
             return $articles; }*/
        
        
        
        $userId=$this->getUser()->getId();
        
       // $posts = json_decode(file_get_contents('http://192.168.128.13:8081/d110005/post/findByIdJournalist/'.$userId),true);
        
      //  $posts = $posts['post'];
        
        
       // var_dump($posts[0]['idState']['idState']);
        
       // var_dump($posts);
        
        
        $tabPostsPublished = new \Doctrine\Common\Collections\ArrayCollection() ;
        $tabPostsSent = new \Doctrine\Common\Collections\ArrayCollection() ;
       /* foreach ($posts as $post) {
            
            $article = new Post($post['subject'],$post['content'],$post['idCategory']);
            if($post['idState']['idState']== 2)
            {
                $tabPostsPublished->add($article);
            }
            else
            {
                $tabPostsSent->add($article);
            }
            
        }*/
        
        
        
        $session = $this->get('session');
        $session->set('tabPostsPublished',$tabPostsPublished);
        $session->set('tabPostsSent',$tabPostsSent);
    
    }

}

?>